// 客户数据


  





// 封装在IIFE中以避免全局变量污染
(function() {
    // 初始化商品数据
    window.productData = JSON.parse(localStorage.getItem('productData')) || [
        { id: 1, name: '排骨', category: '猪肉', defaultPrice: 35.0, costPrice: 25.0 },
        { id: 2, name: '猪脚', category: '猪肉', defaultPrice: 22.0, costPrice: 15.0 },
        { id: 3, name: '三层', category: '猪肉', defaultPrice: 28.0, costPrice: 20.0 },
        { id: 4, name: '瘦肉', category: '猪肉', defaultPrice: 27.0, costPrice: 18.0 },
        { id: 5, name: '腿肉', category: '猪肉', defaultPrice: 26.0, costPrice: 17.0 },
        { id: 6, name: '龙骨', category: '猪肉', defaultPrice: 18.0, costPrice: 10.0 },
        { id: 7, name: '大健', category: '猪肉', defaultPrice: 24.0, costPrice: 16.0 },
        { id: 8, name: '小健', category: '猪肉', defaultPrice: 25.0, costPrice: 17.0 },
        { id: 9, name: '大骨', category: '猪肉', defaultPrice: 15.0, costPrice: 8.0 },
        { id: 10, name: '心肺', category: '内脏', defaultPrice: 12.0, costPrice: 6.0 },
        { id: 11, name: '腰子', category: '内脏', defaultPrice: 20.0, costPrice: 12.0 },
        { id: 12, name: '猪肝', category: '内脏', defaultPrice: 12.0, costPrice: 7.0 },
        { id: 13, name: '肝炎', category: '其他', defaultPrice: 15.0, costPrice: 9.0 },
        { id: 14, name: '大肠', category: '内脏', defaultPrice: 18.0, costPrice: 10.0 },
        { id: 15, name: '小肠', category: '内脏', defaultPrice: 16.0, costPrice: 9.0 },
        { id: 16, name: '猪头', category: '猪肉', defaultPrice: 18.0, costPrice: 11.0 },
        { id: 17, name: '猪舌头', category: '猪肉', defaultPrice: 28.0, costPrice: 18.0 },
        { id: 18, name: '二刀', category: '猪肉', defaultPrice: 26.0, costPrice: 17.0 },
        { id: 19, name: '头骨', category: '猪肉', defaultPrice: 10.0, costPrice: 5.0 },
        { id: 20, name: '头皮', category: '猪肉', defaultPrice: 12.0, costPrice: 6.0 },
        { id: 21, name: '肥油', category: '猪肉', defaultPrice: 8.0, costPrice: 3.0 },
        { id: 22, name: '板油', category: '猪肉', defaultPrice: 10.0, costPrice: 4.0 }
    ];

    // 从本地存储加载商品成本价
    window.productCostPrices = JSON.parse(localStorage.getItem('productCostPrices')) || {};

    // 初始化商品成本价（如果是首次加载）
    if (Object.keys(productCostPrices).length === 0) {
        productData.forEach(product => {
            productCostPrices[product.name] = product.costPrice || 0;
        });
        localStorage.setItem('productCostPrices', JSON.stringify(productCostPrices));
    }

    // 从本地存储加载客户数据
    window.pigSalesCustomers = JSON.parse(localStorage.getItem('customers')) || [];
    // 注意：不再提供默认客户数据，确保数据完全来自localStorage
    

    // 从本地存储加载商品价格
    window.productPrices = JSON.parse(localStorage.getItem('productPrices')) || {};

    // 初始化商品价格（如果是首次加载）
    if (Object.keys(productPrices).length === 0) {
        productData.forEach(product => {
            productPrices[product.name] = product.defaultPrice;
        });
        localStorage.setItem('productPrices', JSON.stringify(productPrices));
    }
})();

// 加载商品价格
function loadProductPrices() {
    const productItems = document.querySelectorAll('.product-card');

    productItems.forEach(item => {
        const name = item.querySelector('.product-name').textContent;
        const priceInput = item.querySelector('.price-input');

        // 优先使用已保存的价格，其次使用默认价格
        const product = productData.find(p => p.name === name);
        if (product) {
            // 检查是否有已保存的价格
            if (productPrices[name] !== undefined) {
                priceInput.value = productPrices[name];
            } else {
                // 使用默认价格
                priceInput.value = product.defaultPrice;
                productPrices[name] = product.defaultPrice;
                localStorage.setItem('productPrices', JSON.stringify(productPrices));
            }
        }

        // 添加价格变化事件监听
        priceInput.addEventListener('change', function() {
            const newPrice = parseFloat(priceInput.value) || 0;
            if (newPrice >= 0) {
                // 保存新价格
                productPrices[name] = newPrice;
                localStorage.setItem('productPrices', JSON.stringify(productPrices));
                // 触发金额更新
                const weightInput = item.querySelector('.weight-input');
                const amountElement = item.querySelector('.amount');
                const price = parseFloat(priceInput.value) || 0;
                const weight = parseFloat(weightInput.value) || 0;
                const amount = price * weight;
                amountElement.textContent = amount.toFixed(2);
                updateTotal(); // 更新总计
            }
        });
    });
}

// 更新总计金额
function updateTotal() {
    const productItems = document.querySelectorAll('.product-card');
    const totalAmountElement = document.querySelector('.total-amount strong');
    let total = 0;
    productItems.forEach(item => {
        const amount = parseFloat(item.querySelector('.amount').textContent) || 0;
        total += amount;
    });
    totalAmountElement.textContent = total.toFixed(2);
}

// 生成商品列表
function generateProductList() {
    const productGrid = document.getElementById('product-grid');
    if (!productGrid) return;

    productGrid.innerHTML = '';

    productData.forEach(product => {
        const productCard = document.createElement('div');
        productCard.className = 'product-card';
        productCard.innerHTML = `
            <div class="product-info">
                <div class="product-name">${product.name}</div>
            </div>
            <div class="product-price">
                <div class="price-input-container">
                    <input type="number" class="price-input" step="0.01" min="0" placeholder="价格">
                    <span class="input-unit">元/公斤</span>
                </div>
            </div>
            <div class="product-weight">
                <div class="price-input-container">
                    <input type="number" class="weight-input" step="0.01" placeholder="重量">
                    <span class="input-unit">公斤</span>
                </div>
            </div>
            <div class="product-amount">
                <span class="amount-label">金额:</span>
                <span class="amount">0.00</span>
                <span class="amount-unit">元</span>
            </div>
        `;
        productGrid.appendChild(productCard);
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('猪肉销售系统已加载');
    // 生成商品列表
    generateProductList();
    // 初始化客户选择下拉框
    initCustomerSelector();
    // 初始化保存按钮事件
    initSaveButton();
    // 加载保存的商品价格
    loadProductPrices();

    // 添加定期刷新客户数据的功能，确保数据同步
    setInterval(initCustomerSelector, 5000); // 每5秒刷新一次
    console.log('已启用客户数据自动刷新功能');

    // 检查是否有SheetJS库，如果没有则加载
    if (typeof XLSX === 'undefined') {
        console.log('加载SheetJS库...');
        const script = document.createElement('script');
        script.src = 'https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js';
        script.onload = function() {
            console.log('SheetJS库加载完成');
            initImportButtons(); // 库加载完成后初始化导入按钮
        };
        document.head.appendChild(script);
    } else {
        initImportButtons(); // 如果库已加载，直接初始化导入按钮
    }

    // 初始化导入按钮
    function initImportButtons() {
          const importCustomerBtn = document.getElementById('import-customer-btn');
          const importAllPricesBtn = document.getElementById('import-all-prices-btn');
          const fileUpload = document.getElementById('file-upload');

        if (importCustomerBtn && importAllPricesBtn && fileUpload) {
            // 导入客户按钮点击事件
            importCustomerBtn.addEventListener('click', function() {
                fileUpload.dataset.importType = 'customer';
                fileUpload.click();
            });

            // 同时导入价格和成本价按钮点击事件
            if (importAllPricesBtn) {
                importAllPricesBtn.addEventListener('click', function() {
                    fileUpload.dataset.importType = 'allPrices';
                    fileUpload.click();
                });
            }

            // 文件上传变化事件
            fileUpload.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (!file) return;

                const importType = this.dataset.importType;
                const reader = new FileReader();
                const fileExtension = file.name.split('.').pop().toLowerCase();

                reader.onload = function(e) {
                    try {
                        let workbook;
                        
                        // 根据文件类型选择不同的读取方式
                        if (fileExtension === 'csv') {
                            // 对于CSV文件，尝试使用UTF-8编码
                            const text = e.target.result;
                            // 使用SheetJS解析CSV文本
                            workbook = XLSX.read(text, { type: 'string', codepage: 65001 }); // 65001 是UTF-8编码
                        } else {
                            // 对于Excel文件，使用二进制方式读取
                            const data = new Uint8Array(e.target.result);
                            workbook = XLSX.read(data, { type: 'array' });
                        }

                        const firstSheetName = workbook.SheetNames[0];
                        const worksheet = workbook.Sheets[firstSheetName];
                        const jsonData = XLSX.utils.sheet_to_json(worksheet);

                        if (importType === 'customer') {
                            importCustomers(jsonData);
                        } else if (importType === 'allPrices') {
                            importAllProductPrices(jsonData);
                        }

                        // 重置文件上传输入
                        fileUpload.value = '';
                    } catch (error) {
                        alert('文件解析错误: ' + error.message);
                        console.error('文件解析错误:', error);
                    }
                };

                // 根据文件类型选择不同的读取方法
                if (fileExtension === 'csv') {
                    reader.readAsText(file, 'UTF-8');
                } else {
                    reader.readAsArrayBuffer(file);
                }
            });
        }
    }

    // 导入客户数据
    function importCustomers(customerData) {
        if (!Array.isArray(customerData)) {
            alert('客户数据格式不正确');
            return;
        }

        // 过滤有效的客户数据
        const validCustomers = customerData.filter(customer => {
            // 客户数据至少需要包含name字段
            return customer && typeof customer.name === 'string' && customer.name.trim() !== '';
        }).map((customer, index) => {
            return {
                id: customer.id || index + 1,
                name: customer.name.trim()
            };
        });

        if (validCustomers.length === 0) {
            alert('没有找到有效的客户数据');
            return;
        }

        // 保存到localStorage
        window.pigSalesCustomers = validCustomers;
        localStorage.setItem('customers', JSON.stringify(validCustomers));

        // 更新客户选择下拉框
        initCustomerSelector();

        alert(`成功导入 ${validCustomers.length} 个客户`);
        console.log('客户导入成功:', validCustomers);
    }

    // 导入商品价格数据
    function importProductPrices(priceData) {
        if (!Array.isArray(priceData)) {
            alert('商品价格数据格式不正确');
            return;
        }

        // 过滤有效的价格数据
        const validPrices = {};
        let validCount = 0;

        priceData.forEach(item => {
            if (item && typeof item.name === 'string' && item.name.trim() !== '' && !isNaN(item.price)) {
                const productName = item.name.trim();
                const price = parseFloat(item.price);
                if (price >= 0) {
                    validPrices[productName] = price;
                    validCount++;
                }
            }
        });

        if (validCount === 0) {
            alert('没有找到有效的商品价格数据');
            return;
        }

        // 合并到现有价格数据
        Object.assign(window.productPrices, validPrices);
        localStorage.setItem('productPrices', JSON.stringify(window.productPrices));

        // 更新商品价格UI
        loadProductPrices();

        alert(`成功导入 ${validCount} 个商品价格`);
        console.log('商品价格导入成功:', validPrices);
    }

    // 同时导入商品价格和成本价数据
    function importAllProductPrices(allPriceData) {
        if (!Array.isArray(allPriceData)) {
            alert('商品价格和成本价数据格式不正确');
            return;
        }

        // 过滤有效的价格和成本价数据
        const validPrices = {};
        const validCostPrices = {};
        let priceCount = 0;
        let costPriceCount = 0;

        allPriceData.forEach(item => {
            if (item && typeof item.name === 'string' && item.name.trim() !== '') {
                const productName = item.name.trim();

                // 验证并导入价格
                if (!isNaN(item.price)) {
                    const price = parseFloat(item.price);
                    if (price >= 0) {
                        validPrices[productName] = price;
                        priceCount++;
                    }
                }

                // 独立验证并导入成本价
                if (!isNaN(item.costPrice)) {
                    const costPrice = parseFloat(item.costPrice);
                    if (costPrice >= 0) {
                        validCostPrices[productName] = costPrice;
                        costPriceCount++;
                    }
                }
            }
        });

        let message = '';

        // 处理价格数据
        if (Object.keys(validPrices).length > 0) {
            Object.assign(window.productPrices, validPrices);
            localStorage.setItem('productPrices', JSON.stringify(window.productPrices));
            loadProductPrices();
            message += `成功导入 ${priceCount} 个商品价格`;
        }

        // 处理成本价数据
        if (Object.keys(validCostPrices).length > 0) {
            Object.assign(window.productCostPrices, validCostPrices);
            localStorage.setItem('productCostPrices', JSON.stringify(window.productCostPrices));

            // 更新商品数据中的成本价
            productData.forEach(product => {
                if (validCostPrices[product.name] !== undefined) {
                    product.costPrice = validCostPrices[product.name];
                }
            });
            localStorage.setItem('productData', JSON.stringify(productData));

            if (message !== '') {
                message += ` 和 ${costPriceCount} 个商品成本价`;
            } else {
                message += `成功导入 ${costPriceCount} 个商品成本价`;
            }
        }

        if (message === '') {
            message = '没有找到有效的商品价格或成本价数据';
        }
        alert(message);
        console.log('商品价格和成本价导入成功:', { validPrices, validCostPrices });
    }

    // 导入商品成本价数据
    function importProductCostPrices(costPriceData) {
        if (!Array.isArray(costPriceData)) {
            alert('商品成本价数据格式不正确');
            return;
        }

        // 过滤有效的成本价数据
        const validCostPrices = {};
        let validCount = 0;

        costPriceData.forEach(item => {
            if (item && typeof item.name === 'string' && item.name.trim() !== '' && !isNaN(item.costPrice)) {
                const productName = item.name.trim();
                const costPrice = parseFloat(item.costPrice);
                if (costPrice >= 0) {
                    validCostPrices[productName] = costPrice;
                    validCount++;
                }
            }
        });

        if (validCount === 0) {
            alert('没有找到有效的商品成本价数据');
            return;
        }

        // 合并到现有成本价数据
        Object.assign(window.productCostPrices, validCostPrices);
        localStorage.setItem('productCostPrices', JSON.stringify(window.productCostPrices));

        // 更新商品数据中的成本价
        productData.forEach(product => {
            if (validCostPrices[product.name] !== undefined) {
                product.costPrice = validCostPrices[product.name];
            }
        });
        localStorage.setItem('productData', JSON.stringify(productData));

        alert(`成功导入 ${validCount} 个商品成本价`);
        console.log('商品成本价导入成功:', validCostPrices);
    }

    // 获取所有商品卡片
    const productItems = document.querySelectorAll('.product-card');
    // 获取总计金额元素
    const totalAmountElement = document.querySelector('.total-amount strong');

    // 为每个商品行添加事件监听
    productItems.forEach((item, index) => {
        const priceInput = item.querySelector('.price-input');
        const weightInput = item.querySelector('.weight-input');
        const amountElement = item.querySelector('.amount');

        // 计算金额并更新显示
        function updateAmount() {
            const price = parseFloat(priceInput.value) || 0;
            const weight = parseFloat(weightInput.value) || 0;
            const amount = price * weight;
            amountElement.textContent = amount.toFixed(2);
            updateTotal(); // 更新总计
        }

        // 为价格和重量输入框添加事件监听
        priceInput.addEventListener('input', updateAmount);
        priceInput.addEventListener('change', updateAmount);
        weightInput.addEventListener('input', updateAmount);
        weightInput.addEventListener('change', updateAmount);

        // 回车键移动到下一个重量输入框
        weightInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                // 获取所有商品行
                const allRows = Array.from(document.querySelectorAll('.product-card'));
                // 找到当前行的索引
                const currentIndex = allRows.indexOf(item);
                // 如果不是最后一行，则移动到下一行
                if (currentIndex < allRows.length - 1) {
                    const nextRow = allRows[currentIndex + 1];
                    const nextWeightInput = nextRow.querySelector('.weight-input');
                    if (nextWeightInput) {
                        nextWeightInput.focus();
                    }
                }
            }
        });

        // 初始化时计算一次金额
        updateAmount();
    });


});

// 获取当前销售记录
function getCurrentSaleRecord() {
    const customerSelect = document.getElementById('customer-select');
    const customerName = customerSelect ? customerSelect.options[customerSelect.selectedIndex].text : '未知客户';
    const date = new Date().toLocaleString();
    const productItems = document.querySelectorAll('.product-card');
    const totalAmount = parseFloat(document.querySelector('.total-amount strong').textContent) || 0;

    const products = Array.from(productItems).map(item => {
        const name = item.querySelector('.product-name').textContent;
        const price = parseFloat(item.querySelector('.price-input').value) || 0;
        const weight = parseFloat(item.querySelector('.weight-input').value) || 0;
        const amount = parseFloat(item.querySelector('.amount').textContent) || 0;
        
        // 获取商品的成本价
        const costPrice = window.productCostPrices[name] || 0;
        const profit = (price - costPrice) * weight;
        
        return {
            name,
            price,
            weight,
            amount,
            costPrice,
            profit
        };
    });

    return {
        customerName,
        date,
        products,
        totalAmount
    };
}

// 导出销售记录到Excel文件
function exportToExcel() {
    // 检查是否有销售记录
    const saleRecord = getCurrentSaleRecord();
    if (!saleRecord || saleRecord.products.every(p => p.weight === 0)) {
        alert('没有可导出的销售记录，请添加商品重量');
        return;
    }
    // 获取导出格式
    const formatSelect = document.getElementById('export-format');
    const exportFormat = formatSelect ? formatSelect.value : 'xlsx';
    const currentSale = getCurrentSaleRecord();
    if (!currentSale) {
        alert('没有可导出的销售记录');
        return;
    }
    const salesRecords = [currentSale];

    // 检查SheetJS库是否加载
    if (typeof XLSX === 'undefined') {
        alert('SheetJS库未加载，请检查网络连接或刷新页面');
        return;
    }
    
    // 准备Excel数据
    const worksheetData = [];
    // 添加表头
    worksheetData.push(['客户名称', '日期', '商品名称', '单价 (元/公斤)', '重量 (公斤)', '金额 (元)', '总金额 (元)']);
    
    // 添加销售记录数据
    salesRecords.forEach(record => {
        record.products.forEach(product => {
            const rowData = [
                record.customerName,
                record.date,
                product.name,
                product.price,
                product.weight,
                product.amount,
                record.totalAmount
            ];
            worksheetData.push(rowData);
        });
        // 添加空行分隔不同的销售记录
        worksheetData.push([]);
    });
    
    // 创建工作簿和工作表
    const workbook = XLSX.utils.book_new();
    const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);
    
    // 调整列宽
    const wscols = [
        { wch: 15 }, // 客户名称
        { wch: 20 }, // 日期
        { wch: 15 }, // 商品名称
        { wch: 15 }, // 单价
        { wch: 15 }, // 重量
        { wch: 15 }, // 金额
        { wch: 15 }  // 总金额
    ];
    worksheet['!cols'] = wscols;
    
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, '销售记录');
    
    // 获取客户名称和日期
    const customerSelect = document.getElementById('customer-select');
    const customerName = customerSelect.options[customerSelect.selectedIndex].text || '未知客户';
    const date = new Date();
    const dateStr = `${date.getFullYear()}${(date.getMonth()+1).toString().padStart(2,'0')}${date.getDate().toString().padStart(2,'0')}`;
    const fileNameBase = `${customerName}_${dateStr}`;

    if (exportFormat === 'xlsx') {
        // 导出Excel文件
        const fileName = `${fileNameBase}.xlsx`;
        XLSX.writeFile(workbook, fileName);
    } else if (exportFormat === 'txt') {
        // 导出TXT文件
        let txtContent = '客户名称: ' + customerName + '\n';
        txtContent += '日期: ' + date.toLocaleString() + '\n';
        txtContent += '\n====================================\n';
        txtContent += '商品名称    单价(元/公斤)    重量(公斤)    金额(元)\n';
        txtContent += '------------------------------------\n';

        currentSale.products.forEach(product => {
            txtContent += product.name.padEnd(12) + 
                          product.price.toFixed(2).padEnd(16) + 
                          product.weight.toFixed(2).padEnd(14) + 
                          product.amount.toFixed(2) + '\n';
        });

        txtContent += '------------------------------------\n';
        txtContent += '总金额: ' + currentSale.totalAmount.toFixed(2) + ' 元\n';
        txtContent += '====================================\n';

        const blob = new Blob([txtContent], { type: 'text/plain;charset=utf-8' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `${fileNameBase}.txt`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(link.href);
    }
}

// 初始化客户选择下拉框
function initCustomerSelector() {
    const customerSelector = document.getElementById('customer-select');
    // 检查元素是否存在
    if (!customerSelector) {
        // 检查是否存在客户选择器元素
        console.log('当前页面没有客户选择器元素，跳过初始化');
        return;
    }
    // 保存当前选中值
    const selectedValue = customerSelector.value;

    // 清空现有选项
    customerSelector.innerHTML = '';

    // 添加默认选项
    const defaultOption = document.createElement('option');
    defaultOption.value = '';
    defaultOption.textContent = '-- 请选择客户 --';
    defaultOption.disabled = true;
    customerSelector.appendChild(defaultOption);

    // 从本地存储重新加载客户数据
    window.pigSalesCustomers = JSON.parse(localStorage.getItem('customers')) || [];

    // 如果没有客户数据，不添加默认客户
    if (pigSalesCustomers.length === 0) {
        console.log('没有找到客户数据，下拉菜单将仅显示默认选项');
    }

    // 添加客户选项
    pigSalesCustomers.forEach(customer => {
        const option = document.createElement('option');
        option.value = customer.name;
        option.textContent = customer.name;
        customerSelector.appendChild(option);
    });

    // 恢复选中状态
    if (selectedValue && pigSalesCustomers.some(c => c.name === selectedValue)) {
        customerSelector.value = selectedValue;
    } else {
        customerSelector.value = '';
    }
}

// 导出今日JSON销售记录
function exportTodayJson() {
    // 获取今天的日期（不含时间）
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);

    // 从本地存储获取所有销售记录
    let salesRecords = JSON.parse(localStorage.getItem('salesRecords') || '[]');

    // 筛选今日的销售记录
    const todaySales = salesRecords.filter(record => {
        const recordDate = new Date(record.date);
        return recordDate >= today && recordDate < tomorrow;
    });

    // 转换为JSON字符串
    const jsonStr = JSON.stringify(todaySales, null, 2);

    // 通过提示框显示JSON
    alert('今日销售记录JSON:\n\n' + jsonStr);
}

// 初始化保存按钮事件
function initSaveButton() {
    const saveButton = document.getElementById('save-btn');
    if (saveButton) {
        // 点击事件处理程序
        function handleSaveClick() {
            const customerSelect = document.getElementById('customer-select');
            const selectedCustomerId = customerSelect.value;
            const selectedCustomerName = customerSelect.options[customerSelect.selectedIndex].text;

            // 验证客户选择
            if (!selectedCustomerId) {
                alert('请选择客户');
                return;
            }

            // 收集商品数据
            const productItems = document.querySelectorAll('.product-card');
            const products = [];
            let hasValidProduct = false;

            productItems.forEach(item => {
                const name = item.querySelector('.product-name').textContent;
                const price = parseFloat(item.querySelector('.price-input').value) || 0;
                const weight = parseFloat(item.querySelector('.weight-input').value) || 0;
                const amount = parseFloat(item.querySelector('.amount').textContent) || 0;

                if (weight !== 0) {
                    products.push({
                        name,
                        price,
                        weight,
                        amount
                    });
                    hasValidProduct = true;
                }
            });

            // 验证是否有有效商品
            if (!hasValidProduct) {
                alert('请至少输入一个商品的重量（不能为0）');
                return;
            }

            // 创建销售记录
            const saleRecord = {
                id: Date.now(), // 使用时间戳作为唯一ID
                customerId: selectedCustomerId,
                customerName: selectedCustomerName,
                date: new Date().toLocaleString(),
                products: products,
                totalAmount: parseFloat(document.querySelector('.total-amount strong').textContent) || 0
            };

            // 保存销售记录到本地存储
            let salesRecords = JSON.parse(localStorage.getItem('salesRecords') || '[]');
            salesRecords.push(saleRecord);
            localStorage.setItem('salesRecords', JSON.stringify(salesRecords));

            // 显示操作成功提示
            alert('销售记录保存成功！\n\n客户: ' + selectedCustomerName + '\n日期: ' + saleRecord.date + '\n总金额: ¥' + saleRecord.totalAmount.toFixed(2));

            // 自动导出销售记录
            exportToExcel();

            // 清空重量输入
            productItems.forEach(item => {
                item.querySelector('.weight-input').value = '';
                item.querySelector('.amount').textContent = '0.00';
            });
            updateTotal();
        }

        // 绑定点击事件
        saveButton.addEventListener('click', handleSaveClick);

        // 添加键盘快捷键监听 (Ctrl+S)
        document.addEventListener('keydown', function(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                e.preventDefault(); // 阻止默认的保存行为
                handleSaveClick();
               
            }
        });
    }

    // 初始化导出按钮事件
    const exportButton = document.getElementById('export-btn');
    if (exportButton) {
        exportButton.addEventListener('click', exportToExcel);
    }

    // 初始化导出今日JSON按钮事件
    const exportTodayJsonButton = document.getElementById('export-today-json-btn');
    if (exportTodayJsonButton) {
        exportTodayJsonButton.addEventListener('click', exportTodayJson);
    }

    // 添加导出格式选择
    const controlsSection = document.querySelector('.controls-section');
    if (controlsSection) {
        const formatSelectContainer = document.createElement('div');
        formatSelectContainer.className = 'export-format';
        formatSelectContainer.innerHTML = `
            <label for="export-format">导出格式:</label>
            <select id="export-format">
                <option value="xlsx">Excel (xlsx)</option>
                <option value="txt">文本文件 (txt)</option>
            </select>
        `;
        controlsSection.appendChild(formatSelectContainer);
    }
}
